package com.edu.controller;

import com.edu.bean.Book;
import com.edu.serivce.BookService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 书籍控制器类，处理与书籍相关的HTTP请求
 */
@Controller
@RequestMapping("/book")
public class BookController {

    /**
     * 注入书籍服务层实例
     */
    @Resource
    private BookService bookService;

    /**
     * 处理获取书籍列表的请求
     *
     * @param book      书籍对象，包含查询条件（如书名、作者、类型）
     * @param beginDate 起始日期，用于筛选书籍的出版时间
     * @param endDate   结束日期，用于筛选书籍的出版时间
     * @param pageNum   当前页码，默认值为1
     * @param pageSize  每页显示的数量，默认值为10
     * @return 分页后的书籍信息，包括总记录数、当前页数据等
     */
    @RequestMapping("/getBooks")
    @ResponseBody
    public Object getBooks(Book book, Date beginDate, Date endDate,
                           @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                           @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 调用服务层方法获取书籍列表
        Page<Book> books = (Page<Book>) bookService.selectBooks(book, beginDate, endDate);

        // 返回分页信息
        return books.toPageInfo();
    }

    @PostMapping("/addBook")
    public String addBook(Book book, MultipartFile mf, Model model){
        if(mf == null || mf.isEmpty() || !mf.getContentType().contains("image")){
            model.addAttribute("msg","必须选择书的封面，且为jpg png格式");
            return "/addBook.jsp";
        }
        //复制文件
        try {
            String fileName = mf.getOriginalFilename();
            String newName = UUID.randomUUID()+fileName;
            String visitPath = "/SSM/bookCover/"+newName;
            String savePath = "c:/bookCover/"+newName;
            book.setBookCover(visitPath);
            mf.transferTo(new File(savePath));
            bookService.addBook(book);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/books";
    }

    @RequestMapping("deleteBook")
    @ResponseBody
    public String deleteBook(int bookId){
        //删除书之前，应该先把书德路径查出来
        Book book =bookService.selectBookById(bookId);
        int result = bookService.delBook(bookId);
        if (result == 1){
            String path = book.getBookCover();
            String[] strs = path.split("bookCover/");
            String realPath = "c:/bookCover/"+strs[1];
            File file = new File(realPath);
            if (!strs[1].equals("default.jpg")){
                file.delete();
            }
            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping("/update")
    public String updatePage(int bookId,Model model){
        Book book = bookService.selectBookById(bookId);
        model.addAttribute("book",book);
        return "forward:/WEB-INF/updateBook.jsp";
    }

    @RequestMapping("/updateBook")
    public String update(Book book,MultipartFile mf){
        bookService.updateBook(book);
        if(mf != null && !mf.isEmpty() && mf.getContentType().contains("image")){
            book = bookService.selectBookById(book.getBookId());
            //修改图片
            //把服务器里保存的 原始的图片给删除掉
            System.out.println(book);
            String path = book.getBookCover();
            System.out.println(book.getBookCover());
            String[] strs = path.split("bookCover/");
            String realPath = "c:/bookCover/"+strs[1];
            File file = new File(realPath);
            if(!strs[1].equals("default.jpg")){
                file.delete();
            }
            //新图片上传到服务器
            String fileName = mf.getOriginalFilename();
            String newName = UUID.randomUUID()+fileName;
            String visitPath = "/SSM/bookCover/"+newName;
            String savePath = "c:/bookCover/"+newName;
            try {
                mf.transferTo(new File(savePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            bookService.updateBookCover(book.getBookId(),visitPath);
        }
        return "redirect:/books";
    }
}
